<?php
/**
 * Created by PhpStorm.
 * User: muhe0
 * Date: 2017/4/18
 * Time: 5:55
 */

namespace LDL\Twspider\C;

/**
 * 可以在多个WOKER之间同步的方法 支持PThread > 3.0
 * Class ReentrantLock
 * @package LDL\Twspider\C
 */
class ReentrantLock extends  \Threaded
{
    private $_locked=-1 ;
    function __construct()
    {
    //    echo "全局锁";确认打出一个
    }

    public function  lock(){
        $this->synchronized(function() {
            while($this->_locked===true)
              {
                  if(IN_DEBUG){
                      echo "Thread ".\Thread::getCurrentThreadId()." wait \n ";
                  }
                  $this->wait();
                  if( $this->_locked===false && IN_DEBUG){
                      echo "Thread ".\Thread::getCurrentThreadId()." resume \n ";
                  }
              }
             $this->_locked= true;

        });


    }

    public function  unlock(){
        $this->synchronized(function(){
            $this->_locked=false;
            $this->notify();
        });


    }

  /*  public function wait(){
        parent::wait() ;
        $this->_locked=false ;
    }*/

}